package com.zxb.core.util;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author Zxb
 */
public class AesUtil {
    public static final byte[] KEY = "wWU32GonOvmIjVZM8uNFx75EQHPSD9bp".getBytes();

    /**
     * 生成一个256位的AES密钥
     */
    private static SecretKey generateKey() throws Exception {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(256);
        return keyGen.generateKey();
    }

    /**
     * 转换为SecretKeySpec，以便与Cipher一起使用
     *
     * @param key
     * @return
     */
    private static SecretKeySpec getSecretKeySpec(byte[] key) {
        return new SecretKeySpec(key, "AES");
    }

    /**
     * 字节数组转16进制字符串
     *
     * @param bytes
     * @return
     */
    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            // 将每个字节转换为两位的十六进制数，并添加到StringBuilder中
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    /**
     * 16进制字符串转字节数组
     *
     * @param hexString
     * @return
     */
    public static byte[] hexToBytes(String hexString) {
        int len = hexString.length();
        byte[] byteArray = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            // 每两个十六进制字符表示一个字节
            String byteString = hexString.substring(i, i + 2);
            // 将十六进制字符串转换为整数，并强制转换为字节
            byteArray[i / 2] = (byte) Integer.parseInt(byteString, 16);
        }
        return byteArray;
    }

    /**
     * AES-256-ECB加密
     *
     * @param plaintext
     * @param key
     * @return
     * @throws Exception
     */
    public static String encrypt(String plaintext, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec secretKeySpec = getSecretKeySpec(key);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
        byte[] encrypted = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encrypted);
        //return bytesToHex(encrypted);
    }

    /**
     * AES-256-ECB解密
     *
     * @param encryptedText
     * @param key
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedText, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        SecretKeySpec secretKeySpec = getSecretKeySpec(key);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        byte[] decoded = Base64.getDecoder().decode(encryptedText);
        //byte[] decoded = hexToBytes(encryptedText);
        byte[] decrypted = cipher.doFinal(decoded);
        return new String(decrypted, StandardCharsets.UTF_8);
    }

    /**
     * 主方法或测试方法中可以调用这些方法
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        String text = "your_base64_encoded_256bit_aes_key_here";
        System.out.println("加密前的字符串："+text);
        String encryptedStr = AesUtil.encrypt(text, KEY);
        System.out.println("加密后的字符串："+encryptedStr);
        String decryptedStr = AesUtil.decrypt(encryptedStr, KEY);
        System.out.println("解密后的字符串："+decryptedStr);
    }
}
